package classloader;

import java.io.File;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;

public class MyClassLoaderByJar extends  URLClassLoader {
    private ModuleManager manager = new ModuleManager();

    public MyClassLoaderByJar(URL[] urls, ModuleManager manager) {
        super(urls);
        this.manager = manager;
    }

    /**
     * 重写了loadClass,优先从内存map查找要加载的类
     */
    protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
        if (manager.getCache().containsKey(name)) {
            return manager.getCache().get(name);
        } else {
            return super.loadClass(name, resolve);
        }
    }

//    public static void main(String[] args) throws Exception {
//        List<String> jarList = new ArrayList<>();
//        jarList.add("/Users/admin/gitee.com/txy-hope/course2-1/jartest/target/jartest-1.0-SNAPSHOT.jar");
//        ModuleManager manager = new ModuleManager();
//        manager.setModuleList(jarList);
//        manager.init();
//        MyClassLoaderByJar myClassLoaderByJar = new MyClassLoaderByJar(new URL[]{new File("/Users/admin/gitee.com/txy-hope/course2-1/jartest/target/jartest-1.0-SNAPSHOT.jar").toURI().toURL()}, manager);
//        Class<?> aClass = myClassLoaderByJar.loadClass("com.lagou.Test");
//        Object test = aClass.newInstance();
//        Method toString = aClass.getDeclaredMethod("toString");
//        Object toStringResult = toString.invoke(test);
//        System.out.println(toStringResult);
//
//        InputStream resourceAsStream = myClassLoaderByJar.getResourceAsStream("test.xml");
//        String str = new String(resourceAsStream.readAllBytes());
//        System.out.println(str);
//    }
}
